package v1

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"zimuzu_cvn_web_api/config"
	"zimuzu_cvn_web_api/model"
	. "zimuzu_cvn_web_api/pkg/e"
	"zimuzu_cvn_web_api/pkg/errno"
	"zimuzu_cvn_web_api/router/api"
	"zimuzu_cvn_web_api/router/api/callBack/middleware"
	"zimuzu_cvn_web_api/service"
)

type GatewayAPI struct {
}

func (gateway GatewayAPI) Name() string {
	return "Gateway API"
}

func (gateway GatewayAPI) Bind() {
	GatewayAPI := config.C.Router.Group("/v1/cb/gw", middleware.TrackLog(), middleware.CallBackCheckSign())
	{
		GatewayAPI.POST("recharge", rechargeNotice)
		GatewayAPI.POST("transfer", transferComfirm)
	}
}

//充值通知回调接口
func rechargeNotice(c *gin.Context) {
	var postData model.CoboTransaction
	body, _ := ioutil.ReadAll(c.Request.Body)
	if err := json.Unmarshal(body, &postData); err != nil {
		Log("err", err)
		api.SendResponse(c, errno.OperationFailed, nil)
		return
	}
	//保存通知
	if ok := service.SaveTransferNotice(postData); !ok {
		api.SendResponse(c, errno.OperationFailed, nil)
		return
	}
	errno.OK.Info = "OK"
	api.SendResponse(c, errno.OK, nil)
	return
}

//提现确认回调接口
func transferComfirm(c *gin.Context) {
	var (
		postData model.CoboTransaction
		data     = make(map[string]bool)
	)
	data["ok"] = false
	//获取body参数
	body, _ := ioutil.ReadAll(c.Request.Body)
	if err := json.Unmarshal(body, &postData); err != nil {
		Log("err", err)
		api.SendResponse(c, errno.OperationFailed, nil)
		return
	}
	//提现确认
	if ok := service.ComfirmTransfer(postData); !ok {
		api.SendResponse(c, errno.OperationFailed, nil)
		return
	}
	errno.OK.Info = "OK"
	api.SendResponse(c, errno.OK, nil)
	return
}
